#!/bin/sh /etc/rc.common
#
# Copyright (C) 2021-2022  sirpdboy  <herboy2008@gmail.com> https://github.com/sirpdboy/luci-app-ddns-go 
#
# This file is part of ddns-go .
# 
# This is free software, licensed under the Apache License, Version 2.0 .
#


START=99
USE_PROCD=1

PROG=/usr/bin/ddns-go
CONFDIR=/etc/ddns-go
CONF=/etc/ddns-go/ddnsgo-config.yaml

get_config() {
        config_get_bool enabled $1 enabled 1
	config_get_bool logger $1 logger 1
	config_get port $1 port 9876
}
ddnsgo_prepare() {
	pgrep -f /usr/bin/ddns-go | xargs kill -9 >/dev/null 2>&1 
	logger -t ddns-go -p warn "ddns-go is stop."
}

init_yaml(){
	[ -d $CONFDIR ] || mkdir -p $CONFDIR 2>/dev/null
	cat /usr/share/ddns-go/ddnsgo-default.yaml  > $CONF
}

stop_service() {
	ddnsgo_prepare
}

start_service() {
	ddnsgo_prepare
	config_load ddnsgo
        config_foreach get_config ddnsgo
	[ x$enabled == x1 ] || return 1
	[ -s ${CONF} ] || init_yaml
	logger -t ddns-go -p warn "ddns-go is start."
	echo "ddns-go is start."
	procd_open_instance
	procd_set_param command $PROG -l :$port -f 300 -c "$CONF"
	[ "x$logger" == x1 ] && procd_set_param stderr 1
	procd_set_param respawn
	procd_close_instance
}

service_triggers() {
      procd_add_reload_trigger "ddnsgo"
}
